
<template>
  <div ref="videoPlayer" style="position:relative;">
    <Artplayer class="art-box" @get-instance="getInstance" :option="option" :style="style" />  
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import Artplayer from "./Artplayer.vue";
const videoPlayer = ref(null)
const w = 600, h = 400
const cssText = `
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: absolute !important;
            z-index: 999 !important;
            pointer-events: none !important;
            top: 0 !important;
          `
const style = {
  width: w+"px",
  height: h+"px",
}
const canvas_box = ref(null)
const option = reactive({
  // url: "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
  url: "https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8",
  // setting: true,
  fullscreen: true,
})
onMounted(() => {
  init()
})
document.addEventListener('fullscreenchange', () =>handleFullscreenChange())

function init() {
  let canvas = canvasFunc()
  canvas_box.value = canvas
  // 修改事件监听部分
  const initWatermark = () => {
      checkWatermarkStyle(canvas)
      updateWatermark()
  }
  initWatermark()
  MutationObserverFunc(canvas)
}
function canvasFunc() {
  // 创建水印画布 =====================================================
  const canvas = document.createElement('canvas')
  // 给canvas添加一个id
  canvas.id = 'watermark'
  canvas.style.cssText = cssText
  // 挂载到视频容器
  console.log(videoPlayer.value)
  videoPlayer.value.appendChild(canvas)
  return canvas
}
// 动态更新水印
function updateWatermark() {
    let canvas = canvas_box.value
    if (!canvas) return
    const ctx = canvas.getContext('2d')
    if (!ctx) {
      console.error('无法获取canvas上下文')
      return
    }
    const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement
    if(fullscreenElement) {
      canvas.width = fullscreenElement.offsetWidth
      canvas.height = fullscreenElement.offsetHeight
    } else {
      canvas.width = w
      canvas.height = h
    }
    
    // 铺满屏幕
    createDenseWatermark(ctx, canvas.width, canvas.height) // 绘制水印
    requestAnimationFrame(updateWatermark) // 递归调用
}

// 创建高密度水印
let Angle = [-20, 20, 0]
const randomIndexAngle = Math.floor(Math.random() * Angle.length)
let x_w = [250, 300, 200, 180] // 水印横向间隔
let randomX = Math.floor(Math.random() * x_w.length)
let y_w = [150, 120, 180, 90] // 水印纵向间隔
let randomY = Math.floor(Math.random() * y_w.length)
function createDenseWatermark(ctx, width, height) {
  // let Angle = [-20, 20, 0]
  // const randomIndexAngle = Math.floor(Math.random() * Angle.length)
  // let x_w = [250, 300, 200, 180] // 水印横向间隔
  // let randomX = Math.floor(Math.random() * x_w.length)
  // let y_w = [150, 120, 180, 90] // 水印纵向间隔
  // let randomY = Math.floor(Math.random() * y_w.length)

  ctx.save() // 保存画布状态
  ctx.font = '18px Arial'
  ctx.fillStyle = 'rgba(255,255,255,0.3)'
  
  ctx.rotate(Angle[randomIndexAngle] * Math.PI / 180) // 旋转角度
  const timestamp = new Date().toLocaleTimeString()
  // 矩阵式重复水印
  for (let x = -width; x < width*2; x += x_w[randomX]) {
    for (let y = -height; y < height*2; y += y_w[randomY]) {
      // ctx.fillText(`ID:USER_${Date.now()}`, x, y)
      ctx.fillText(`ID:USER_${timestamp}`, x, y)
    }
  }
  ctx.restore() // 恢复画布状态
  // 添加全屏检测
  if (document.fullscreenElement) {
    ctx.font = '24px Arial' // 全屏时增大字号
  }
}
// 检查样式是否被修改
function checkWatermarkStyle(canvas) {
  const check = () => {
    const computedStyle = getComputedStyle(canvas)
    const violations = [
      computedStyle.position !== 'absolute',
      computedStyle.display === 'none',
      computedStyle.visibility === 'hidden',
      computedStyle.top !== '0px !important',
      computedStyle.left !== '0px !important',
      computedStyle.right !== '0px !important',
      parseFloat(computedStyle.opacity) < 0.5
    ]

    if (violations.some(v => v)) { // 如果有违反，重新设置样式
      canvas.style.cssText = cssText
    }
  }
  // 每秒检查10次（平衡性能与安全性）
  setInterval(check, 100)
}
// 使用MutationObserver保护水印元素不被f12删除
function MutationObserverFunc(canvas) {
  const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      // 防御display属性修改
      // if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
      //   const currentDisplay = getComputedStyle(canvas).display
      //   if (currentDisplay === 'none') {
      //     canvas.style.display = 'block'
      //   }
      // }
      // 禁止在f12后对元素进行删除
      const fullscreenElement = document.fullscreenElement
      const targetContainer = fullscreenElement || videoPlayer.value
      if (!targetContainer.contains(canvas)) { // 如果canvas不在目标容器中，则重新添加
        targetContainer.appendChild(canvas)
      }
    })
  })
  // 修改观察配置
  observer.observe(document.body, {
    attributes: true,         // 观察属性变化
    attributeFilter: ['style'], // 仅观察style属性
    childList: true,          // 原有子节点观察
    subtree: true             // 原有子树观察
  })
}
function handleFullscreenChange() {
  // console.log('handleFullscreenChange')
  if(!canvas_box.value) return
  let canvas = canvas_box.value
  const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement
  // console.log('Fullscreen mode changed', fullscreenElement)
  if(fullscreenElement) { // 进入全屏时重新挂载水印
    console.log('进入全屏状态')
    // console.log(fullscreenElement.nodeName )
    fullscreenElement.appendChild(canvas)
    // 调整水印尺寸
    // 使用setTimeout等待浏览器渲染
    setTimeout(() => {
      canvas.width = fullscreenElement.offsetWidth
      canvas.height = fullscreenElement.offsetHeight
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      createDenseWatermark(ctx, canvas.width, canvas.height)
      console.log(fullscreenElement.offsetHeight, canvas.height)
    }, 100)
  } else { // 退出全屏时
    videoPlayer.value.appendChild(canvas)
    updateWatermark()
  }
}
function getInstance(art) {
  console.info(art);
}

</script>
<style scoped>
.read-the-docs {
  color: #888;
}
 /* 添加全局不可覆盖样式 */
 #watermark {
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  pointer-events: none !important;
}

/* 全屏模式下的水印定位 */
:fullscreen #watermark,
:-webkit-full-screen #watermark,
:-moz-full-screen #watermark {
  position: fixed !important;
  width: 100vw !important;
  height: 100vh !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 2147483647 !important; /* 最大z-index值 */
}
</style>
